const Urls = 'http://192.168.3.254:9006/';//本地
// const Urls = 'https://minivip.pos08.com:4437/'
// const Urls = 'https://minipos.bycpos.com.cn/' // 博亚诚专用


function getUrls() {
	uni.setStorageSync("URL", Urls)
	return Urls;
}

function request(options) {
	let token = uni.getStorageSync('Token'),
	cookie = uni.getStorageSync('Cookies'),
	mSystemAppID = uni.getStorageSync('mSystemAppID')
	options.header = {
		'content-type': 'application/json', // 默认值
		'cookie': cookie,
		'token': token,
		'mSystemAppID' : mSystemAppID
	};
	///我们使用Promise方法来实现调用接口时后面多个.then()的方法
	//只有Promise能实现如同$axios后面连续多个.then()的方法
	return new Promise((reslove, reject) => {
		uni.request({
			...options,
			success: res => {
				//判断我们在使用封装的自定义时第三个参数是否为native
				//当native为true时 我们返回原数据
				if (options.native) {
					reslove(res)
				}
				//当native为false时 我们直接返回data中的数据
				if (res.statusCode === 200) {
					reslove(res.data)
				} else {
					//加入接口参数错误或接口地址错误时 我们返回原错误提示
					reject(res)
				}
			},
			fail: (error) => {

			}
		})
	})
}

//在方法中 第二个参数和第三个参数用ES6新语法来添加默认值
//接口调取get方法
function get(url, data = {}, options = {}) {
	//我们把传过来的参数赋给options，这样我们在使用uni-app
	//this.request()方法时 传递一个参数就可以
	options.url = Urls + url;
	options.data = data;
	options.method = 'get';
	//调用上面自己定义的this.request()方法传递参数
	return request(options)
}
//接口调取post方法
function post(url, data = {}, options = {}) {
	options.url = Urls + url;
	options.data = data;
	options.method = 'post';
	return request(options)
}


function util(url, data, method) {
	let token = uni.getStorageSync('Token'),
			cookie = uni.getStorageSync('Cookies'),
			Url = uni.getStorageSync("URL") || Urls,
			mSystemAppID = uni.getStorageSync('mSystemAppID'),
			url1;
	return new Promise((resolve, reject) => {
		uni.request({
			url: Url + url,
			data: data,
			method: method,
			header: {
				'content-type': 'application/json', // 默认值
				'cookie': cookie,
				'token': token,
				'mSystemAppID': mSystemAppID
			},
			success: (res) => {
				if (url === "XcxShopHome/GetCorpID") {
					return resolve(res.data);
				}
				if (res.data.status == 1 || res.data.msg == 'success' || res.data.Succeed == true) {
					let data = res.data.data || res.data.list || res.data.ResultData || res.data;
					if (url === "WeChatShop/MiniProgramName") {
						return resolve(data);
					}
					if (data != '') {
						if ((typeof data) == 'string') {
							//通过正则表达式来判断接口返回的数据是否是中文字符，(有一小部分接口返回全中文字符的，需要注意)
							var reg = /^[\u4e00-\u9fa5]+$/i; //判断是否全是中文字符
							if (!reg.test(data)) {
								data = JSON.parse(data);
							} else {
								data = data;
							}
						}
					}
					return resolve(data);
				} else {
					let error = res.data.data || res.data.msg || '运行出错'
					uni.hideLoading();
					if (url === 'WeChatShop/GetStockById' || url === 'WeChatShop/MiniProgramName' ||
						url === 'MemberShop/CouponList' || url === 'WeChatShop/GetLastScene' ||
						url === 'MemberShop/CpuonSend') {
						return reject(res)
					} else {
						uni.showToast({
							title: error,
							duration: 2000,
							icon:'none'
						});
						return reject(res)
					}
				}
			},
			fail: (error) => {
				uni.showToast({
					title: error,
					duration: 2000,
					icon:'none'
				});
				uni.hideLoading();
				return reject(error)
			}
		})
	})
};
//支付内容接口
function utils(url, res, reqData) {
	let datas = {
		'orgId': res.orgId, //随行付给合作机构分配的唯一id
		'reqId': res.reqId, //唯一id(用户商自己生成)
		'timestamp': res.timestamp, //请求时间
		'version': '1.0', //版本
		'signType': 'RSA', //签名类型
		'sign': res.sign, //签名结果
		'reqData': reqData, //业务数据
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://openapi-test.tianquetech.com/' + url,
			data: datas,
			method: 'POST',
			header: {
				'content-type': 'application/json',
			},
			success: (res) => {
				resolve(res);
			},
			fail: (error) => {
				console.log(error);
				reject(error);
			}
		})
	})
}
// 登录开始
let parentid = ''; //推荐人
//登录接口
function login2(code) {
	var lastHostid = uni.getStorageSync('lastHostid'); //旧的
	var options = uni.getStorageSync('options');
	options = JSON.stringify(options);
	let FItemID = uni.getStorageSync('stockId');
	let stockId = uni.getStorageSync('stockId');
	//推荐人
	let parentID = uni.getStorageSync('parentID');
	if (parentID != '') {
		parentid = parentID
	} else {
		parentid = 0;
	}
	let codeid = '';
	let Url = uni.getStorageSync("URL") || getUrls();
	var appid = uni.getAccountInfoSync();
	appid = appid.miniProgram.appId;
	let phone = uni.getStorageSync("phone");
	return new Promise((resolve, reject) => {
		uni.request({
			url: Url + 'WeChatShop/OnLogin?code=' + code + '&appid=' + appid + '&hostid=' + lastHostid +
				'&stockid=' + stockId + '&scene=' + options + '&parentID=' + parentid+'&phone='+phone,
			success: res => {
				uni.setStorageSync('sessionid', res.header["Set-Cookie"])
				uni.setStorageSync('Cookies', res.cookies[0]);
				uni.setStorageSync('corpid', res.data.stockdata[0].FCorpID);
				uni.setStorageSync('FItemID', res.data.stockdata[0].FItemID);
				if (res.data.status != 0) {
					uni.setStorageSync('Token', res.data.Token);
					// SaleLogin(res.data.Token).then(res2 => {
					// 	uni.setStorageSync('Token', res2);
					// 	getAuth2(res).then(res => {
					// 		resolve(res)
					// 	})
					// });
				}
				if (res.data.status == 1) {
					uni.setStorageSync('Phone', res.data.data[0].FPhone)
					uni.setStorageSync('userUid', res.data.data[0].FItemID)
					if (res.data.memberdata != null) {
						//会员卡资料
						
						uni.setStorageSync('stockdata', res.data.stockdata[0])
						if (res.data.memberdata.length != 0) {
							uni.setStorageSync('memberdataID', 1)
							uni.setStorageSync('memberdata', res.data.memberdata)
						} else {
							uni.setStorageSync('memberdataID', 0)
							uni.removeStorageSync('memberdata');
						}
					} else {
						uni.setStorageSync('memberdataID', 0)
						uni.removeStorageSync('memberdata');
					}
					getsetting2().then(res => {
						//console.log('getSetting', res);
						resolve(res);
					}).catch(error => {
						//console.log(error)
					});
				} else if (res.data.status == 2) {
					var Fphone = res.data.data[0].FPhone;
					if (Fphone != null) {
						uni.setStorageSync('Phone', res.data.data[0].FPhone)
					}
					userinfo().then(res => {
						//console.log('userInfo', res);
						resolve(loginID = res);
					}).catch(error => {
						//console.log('userInfo', error);
					});
				} else {
					// codeID = 0;
					uni.showModal({
						title: '登录提示',
						content: res.data.msg,
					})
					uni.hideLoading();
					codeid = 0;
					resolve(codeid);
				}
			},
			fail: err => {
				//console.log('OnLogin', err,url);
				// uni.showModal({
				// 	title: '友情提示',
				// 	content: '网络不稳定哦！！',
				// })
				uni.hideLoading();
			}
		})
	})
};
//记录是否有电话号码
function phone() {
	var phoneID = '';
	var phone = uni.getStorageSync('Phone');
	var isBeGranted = uni.getStorageSync("isBeGranted");
	if (isBeGranted == 1) {
		if (phone != '' && phone != null) {
			phoneID = 1;
		} else {
			phoneID = 0;
		}
	}
	uni.setStorageSync("PhoneID", phoneID);
};
//登录
function Login(code) {
	let Appid = uni.getAccountInfoSync(),
		appid = Appid.miniProgram.appId,
		parentID = '',
		scene = uni.getStorageSync('scene'), //当前扫码得到的参数
		Url = uni.getStorageSync("URL") || getUrls(),
		hostid = uni.getStorageSync('hostid'),
		stockId = uni.getStorageSync('stockId'),
		phone = uni.getStorageSync('phone'),
		avatarUrl = uni.getStorageSync('userInfo').avatarUrl,
		nickName = uni.getStorageSync('userInfo').nickName
	// if(id==1){
	// 	appid = 'wx25e041abd4474418'
	// }

	return new Promise((resolve, reject) => {
		uni.request({
			url: Url + 'WeChatShop/OnLogin?code=' + code + '&appid=' + appid + '&hostid=' + hostid +
				'&stockid=' + stockId + '&scene=' + scene + '&parentID=' + parentID + '&phone=' + phone + '&avatarUrl=' + avatarUrl + '&nickName=' + nickName,
			success: (resLogin) => {
				uni.hideLoading();
				if (resLogin.data != null && resLogin.data.status == 0) {
					uni.showToast({
						title: resLogin.data.msg,
						icon: 'none',
						mask: true,
						duration: 2000
					});
					return;
				}
				let Phone = resLogin.data.data[0].FPhone;
				let phoneID = Phone == null ? 0 : 1;
				uni.setStorageSync('mSystemAppID', resLogin.data.mSystemAppID)
				uni.setStorageSync('business_key', resLogin.data.business_key)
				uni.setStorageSync('PhoneID', phoneID)
				uni.setStorageSync('Cookies', resLogin.cookies[0]);
				uni.setStorageSync('Members', {...resLogin.data.memberdata, FPhone: resLogin.data.data[0].FPhone}); //会员卡
				uni.setStorageSync('corpid', resLogin.data.stockdata[0].FCorpID); //公司id
				uni.setStorageSync('LoginID', 1);
				uni.setStorageSync('userInfo', {
					AvatarUrl:resLogin.data.data[0].FAvatarUrl,
					NickName:resLogin.data.memberdata[0].NiName,
					Number:resLogin.data.memberdata[0].Number,
					Phone: resLogin.data.data[0].FPhone,
					MemberID: resLogin.data.data[0].FMemberID,
				});
				if (resLogin.data.status == 2) {
					uni.navigateTo({
						url: '/pages/public/login'
					})
				}
				if (resLogin.data.status != 0) {
					if (resLogin.data.memberdata != null) {
						//会员卡资料
						
						uni.setStorageSync('stockdata', resLogin.data.stockdata[0])
						if (resLogin.data.memberdata.length != 0) {
							uni.setStorageSync('memberdataID', 1)
							uni.setStorageSync('memberdata', resLogin.data.memberdata)
						} else {
							uni.setStorageSync('memberdataID', 0)
							uni.removeStorageSync('memberdata');
						}
					} else {
						uni.setStorageSync('memberdataID', 0)
						uni.removeStorageSync('memberdata');
					}
					resolve(1)
					// this.getAuth(resLogin).then(res => {
					// 	resolve(res)
					// })
				} else {
					resolve(0)
				}
			},
			fail: (error) => {
				console.log('err', error)
				reject(error)
			}
		})
	})
};

function login3(url, data = {}, options = {}) {
	options.url = Urls + url;
	options.data = data;
	options.method = 'get';
	///我们使用Promise方法来实现调用接口时后面多个.then()的方法
	//只有Promise能实现如同$axios后面连续多个.then()的方法
	return new Promise((reslove, reject) => {
		uni.request({
			...options,
			success: res => {
				//判断我们在使用封装的自定义时第三个参数是否为native
				//当native为true时 我们返回原数据
				if (options.native) {
					reslove(res)
				}
				//当native为false时 我们直接返回data中的数据
				if (res.statusCode === 200) {
					uni.setStorageSync('sessionid', res.header["Set-Cookie"])
					uni.setStorageSync('Cookies', res.cookies[0]);
					uni.setStorageSync('Token', res.data.Token);
					uni.setStorageSync('corpid', res.data.stockdata[0].FCorpID);
					reslove(res.data)
				} else {
					//加入接口参数错误或接口地址错误时 我们返回原错误提示
					reject(res)
				}
			},
			fail: (error) => {

			}
		})
	})
}

//登录处理
function getAuth2(resLogin) {
	let status = resLogin.data.status;
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (res) => {
				//判断授权登录是否成功
				// let loginID = '';
				if (res.authSetting['scope.userInfo']) {
					getsetting2().then(res => {
						resolve(res);
					})

				} else {
					resolve(0);
				}
			},
		})
	})
};

//登录处理
function getAuth(resLogin) {
	let status = resLogin.data.status;
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (res) => {
				//判断授权登录是否成功
				// let loginID = '';
				if (res.authSetting['scope.userInfo']) {
					getSetting(status).then(res => {
						resolve(res);
					})
				} else {
					resolve(0);
				}
			},
		})
	})
};

//getSetting 判断是否已授权
function getsetting2() {
	let loginID = '';
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: res => {
				if (res.authSetting['scope.userInfo']) {
					// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
					uni.getUserInfo({
						withCredentials: true,
						lang: "zh_CN",
						success: res2 => {
							//app.globalData.userInfo = res2.userInfo;
							uni.setStorageSync('userInfo', res2.userInfo);
							uni.setStorageSync('MuserInfo', res2.userInfo);
							uni.setStorageSync('isBeGranted', 1)
							phone();
						}
					})
					loginID = 1
				} else {
					uni.setStorageSync('isBeGranted', 0)
					uni.hideLoading();
					loginID = 0;
				}
				resolve(loginID)
			}
		});
	});
};
//getSetting 判断是否已授权
function getSetting(status) {
	let Status = status,
		loginID = 0,
		Appid = uni.getAccountInfoSync(),
		Members = uni.getStorageSync('Members'),
		appid = Appid.miniProgram.appId;
	return new Promise((resolve, reject) => {
		uni.getUserInfo({
			withCredentials: true,
			lang: "zh_CN",
			success: res => {
				// this.$userInfo = res.userInfo;
				// uni.setStorageSync('userInfo', res.userInfo);
				if (Members === '' && Status == 1) {
					//获取会员信息
					MemberData()
				}
				//补充信息
				if (Status == 2) {
					let token = uni.getStorageSync('Token'),
						cookie = uni.getStorageSync('Cookies'),
						Url = uni.getStorageSync("URL"),
						stockId = uni.getStorageSync("stockId");
					let data = {
						encryptedData: res.encryptedData,
						iv: res.iv,
						rawData: res.rawData,
						signature: res.signature,
						stockid: stockId,
						appid: appid,
						parentID: '',
					}
					uni.request({
						url: Url + 'WeChatShop/GetUserInfo',
						data: data,
						method: 'GET',
						header: {
							'content-type': 'application/json', // 默认值
							'auth': token,
							'cookie': cookie,
						},
						success: (Userres) => {
							if (Userres.data.status == 1) {
								if (Members === '') {
									//获取会员信息
									MemberData()
								}
								resolve(1);
							} else {
								uni.removeStorageSync('PhoneID')
								resolve(0);
							}
						},
						fail: (error) => {
							resolve(0);
						}
					})
				} else { //OnLogin接口返回用户信息完整
					loginID = 1;
					resolve(loginID);
				}

			},
		})
	});
};
// Sale/SaleLogin
function SaleLogin(token) {
	let corpid = uni.getStorageSync('corpid'),
		stockId = uni.getStorageSync('stockId'),
		mSystemAppID = uni.getStorageSync('mSystemAppID'),
		Url = uni.getStorageSync("URL");
	return new Promise((resolve, reject) => {
		uni.request({
			url: Url + 'Sale/SaleLogin',
			data: {
				corpid: corpid,
				stockid: stockId,
			},
			method: 'POST',
			header: {
				'token': token,
				'mSystemAppID' : mSystemAppID
			},
			success: (res) => {
				if (res.data.msg == 'fail') {
					uni.showModal({
						title: '提示',
						content: res.data.data
					})
					uni.hideLoading();
				} else {
					resolve(res.data.data.token);
				}
			},
			fail: (error) => {
				console.log(error)
				uni.hideLoading();
			}
		})
	});
};

function aprom(url) {
	let end = '',
		e = '',
		arr = [];
	return new Promise((resolve, reject) => {
		util(url, {}, 'POST').then(res => {
			//console.log(res);
			if (res != []) {
				res.forEach((item, index) => {
					if (item.IvQty != 0 && item.Status != 0) {
						end = item.EndTime;
						// e = app.onCountdown(end);
						if (e.type != 1) {
							arr.push(item);
						}
					}
				})
			}
			resolve(arr);
		}) //.catch(error=>//console.log(error));
	});
};

function MemberData() {
		console.log('MemberData')
	util('MemberShop/GetMemberData', {}, 'GET').then(res => {
		uni.setStorageSync('Members', res)
	})
}
// 登录结束
let tiemDate = '',
	id = '',
	GroupData = '',
	share = '',
	uid = '',
	AcChild = '',
	usersData = '',
	Usets = [],
	usetsArr = '',
	childSet = '',
	goodsData = '',
	acid = '',
	childId = '',
	userInfoUid = '';
/**
 * 获取团购明细数据
 * url => 接口地址
 * data => 接口上传数据
 *  Cdata => return内容数据
 */
function add(url, data, Group) {
	var self = this;
	let Alldata = {};
	GroupData = Group;
	share = Group.share;
	uid = Group.uid;
	id = Group.id;
	AcChild = Group.AcChild;
	return new Promise(function(resolve, reject) {
		util(url, data, 'POST').then(res => {
			//console.log(res);
			let datas = '';
			let musicUrl = '';
			if (Group.share == 0) {
				usersData = res.users;
				datas = res.data;
			} else {
				datas = res;
			}
			let childList = datas.ChildSet; //      
			if (Group.AcChild != 1) {
				data = datas;
				let arr = [];
				if (childList != undefined) {
					for (var i = 0; i < childList.length; i++) {
						arr.push(childList[i].Uid);
					}
				}
				musicUrl = data.FMusicUrl || data.Goods[0].FMusicUrl;
				Usets = arr;
			} else {
				data = datas; //总数据
				usetsArr = datas.users; //参加活动用户数据
				for (var i in usetsArr) {
					Usets.push(usetsArr[i].uid);
				}
				if (Group.id == 1 || Group.share == 0) {
					data = datas;
				} else {
					data = datas.data;
					musicUrl = data.FMusicUrl || data.Goods[0].FMusicUrl;
				}
			}
			if (musicUrl == null) {
				musicUrl = '';
			}
			var goodData = data.Goods[0]; //活动的数据
			childSet = data.ChildSet; //子活动的数据
			if (Group.id != 1 && childSet != null) {
				if (childSet.length > 0) {
					if (Group.uid != '') {
						for (var i in childSet) {
							if (Group.uid == childSet[i].Uid) {
								childId = childSet[i].Childid //子拼团id
							}
						}
					} else {
						childId = data.ChildSet[0].Childid //子拼团id
					}
				} else {
					childId = '' //子拼团id
				}
			} else {
				childId = '' //子拼团id
			}

			let Text = Group.activityTypeID == 0 ? goodData.FIntro : goodData.FRuleIntro;
			let img = goodData.FImages != null ? goodData.FImages :
				'http://minipos.posyun3721.com/marketing/image/rec1.png';
			//时间
			var end = goodData.FEndDate;
			var end2 = goodData.FEndTime;
			let NeedPay = '';
			if (Group.id == 1) {
				end = end
				NeedPay = data.NeedPay;
			} else {
				end = (end + ' ' + end2);
			}
			//砍价的金额计算
			let number = 0;
			if (Group.share == 0) {
				Usets = [];
				for (var i in usersData) {
					Usets.push(usersData[i].uid)
					if (id == 2) {
						number += usersData[i].price;
					}
				}
			}
			//是否收藏
			let coll, collImg;
			if (goodData.IsCollect == true) {
				coll = false;
				collImg = 'http://minipos.posyun3721.com/image/marketing/collect2.png';
			} else {
				coll = true
				collImg = 'http://minipos.posyun3721.com/image/marketing/collect1.png';
			}
			goodsData = goodData;
			acid = data.Acid;
			uni.setStorageSync('childSet', childSet);
			Alldata = {
				goodsData: goodData,
				childSet: childSet,
				childId: childId,
				groupId: data.Acid, //团购id
				residuals: data.IvQty, //剩余数量
				browse: data.ReadCount, //浏览人数
				participate: data.UsedQty, //参与人数
				activiStatus: data.Status,
				text: Text, //
				swiper: [img], //图片
				usersData: usersData,
				usersPrice: number,
				tiemDate: end,
				NeedPay: NeedPay, //秒杀 是否没支付
				Usets: Usets,
				coll: coll,
				collImg: collImg,
				FMusicUrl: musicUrl,
			}
			resolve(Alldata)
		}).catch(error => {
			//console.log(error);
			reject(error);
			uni.showToast({
				title: error.data.msg,
				icon: 'none',
				duration: 3000,
			})
		});
	})
};

//倒计时
function onCountdown(endDateStr) {
	var self = this;
	var data = {};
	//结束时间
	var endDate = new Date(endDateStr);
	//当前时间
	var nowDate = new Date();
	if (endDate <= nowDate) {
		data = {
			type: 1,
			days: 0,
			hours: 0,
			minutes: 0,
			seconds: 0
		}
		//记录该活动时间是否已过期
		uni.setStorageSync('timeOut', 1)
		return data = data;
	}
	//相差的总秒数
	var totalSeconds = parseInt((endDate - nowDate) / 1000);
	//天数
	var days = Math.floor(totalSeconds / (60 * 60 * 24));
	//取模（余数）
	var modulo = totalSeconds % (60 * 60 * 24);
	//小时数
	var hours = Math.floor(modulo / (60 * 60));
	modulo = modulo % (60 * 60);
	//分钟
	var minutes = Math.floor(modulo / 60);
	//秒
	var seconds = modulo % 60;
	data = {
		// acid: acid,
		type: 0,
		days: days,
		hours: hours,
		minutes: minutes,
		seconds: seconds
	}
	return data;
};

//跳转到另一个小程序 （去会员卡小程序处理支付问题）
function miniProgram(url, data) {
	// let token = uni.getStorageSync('Token');
	// develop	开发版	trial	体验版	release	正式版
	uni.navigateToMiniProgram({
		appId: 'wx25e041abd4474418',
		path: url,
		extraData: data,
		envVersion: 'develop',
		success(res) {
			// 打开成功
			console.log('打开成功')
		},
		fail(error) {
			console.log(error)
		}
	})
};


//获取参加子拼团用户的信息
function childUser(data) {
	let self = this;
	let user = [];
	let usersImg = [];
	let userID = 0;
	let usersActAmt = 0;
	let UData = data; //当前子活动的参与人id
	let distributor = ''; //分销人员id
	return new Promise(function(resolve, reject) {
		util('WxUserInfo/GetUserInfo', {
			users: data
		}, 'POST').then(res => {
			//console.log(res);
			let userData = res;
			let userInfo = uni.getStorageSync('MuserInfo'); //当前用户的wx个人信息
			if (share != 0) { //没有发起人员的活动链接
				for (var i in userData) {
					//获取当前用户的id
					if (userInfo.nickName == userData[i].FNiName) {
						userID = 1;
						userInfoUid = userData[i].FItemID
					}
					for (var j in childSet) { //当前子活动的参与用户信息

						//当前用户是否在当前子活动的用户信息当中
						if (childSet[j].Uid == userData[i].FItemID) {
							childSet[j].FAvatarUrl = userData[i].FAvatarUrl;
							childSet[j].FNiName = userData[i].FNiName;
							user.push(childSet[j]);
							distributor = childSet[j].ProWXID;
							let userUid = uni.getStorageSync('userUid');
							if (childSet[j].Uid == userUid) {
								//当前子活动是否拼团/砍价成功；
								if ((childSet[j].GroupQty - childSet[j].ActQty) == 0 && childSet[j]
									.Status == '成功') {
									userID = 2;
								}
							}

						}
					}
				}
			} else {
				for (var i in userData) {
					//获取当前用户的信息
					if (uid == userData[i].FItemID) {
						usersImg.push(userData[i]);
						for (var k in childSet) {
							if (uid == childSet[k].Uid) {
								distributor = childSet[k].ProWXID;
							}
						}
					}
					for (var j in UData) {
						if (UData[j] == userData[i].FItemID) {
							user.push(userData[i]);
						}
					}
				}
				//砍价活动才用
				if (usersData != '' && id == 2) {
					for (var i in user) {
						for (var j in usersData) {
							if (usersData[j].uid == user[i].FItemID) {
								user[i].price = usersData[j].price
							}
							//获取当前用户的id
							if (userInfo.nickName == userData[i].FNiName) {
								userInfoUid = userData[i].FItemID

							}
						}
					}
				}
			}
			let data = {
				user: user, //当前参与活动的用户信息
				usersImg: usersImg, //当前用户的信息
				userID: userID, //是否已参加当前子活动 1=> 已参加 2=> 当前子活动已砍价成功，需要前往支付页面支付
				userInfoUid: userInfoUid, //当前用户的
				usersActAmt: usersActAmt,
				distributor: distributor, //当前子活动的分销人员id
			}
			resolve(data)
		}) //.catch(error=>//console.log(error));
	});
};

var nowFItemID = '',
	loginID = '',
	header = '',
	FPhone = '',
	imgBJ = '';
//判断是否是同一个公司id进来的
function onjudge(FItemID) {
	var login = uni.getStorageSync('LoginID');
	var lastFItemID = uni.getStorageSync('FItemID');
	var lastHostid = uni.getStorageSync('lastHostid'); //旧的
	var nowHostid = uni.getStorageSync('hostid'); //新的

	//console.log('lastHostid:' + lastHostid, 'hostid:' + nowHostid)
	nowFItemID = FItemID;
	// return new Promise((resolve, reject) => {
	// 	
	// 	util(url, {}, 'POST').then(res => {
	// 		//console.log(res);
	// 		if (res != []) {
	// 			res.forEach((item, index) => {
	// 				if (item.IvQty != 0 && item.Status != 0) {
	// 					end = item.EndTime;
	// 					// e = app.onCountdown(end);
	// 					if (e.type != 1) {
	// 						arr.push(item);
	// 					}
	// 				}
	// 			})
	// 		}
	// 		resolve(arr);
	// 	}) //.catch(error=>//console.log(error));
	// });
	return new Promise((resolve, reject) => {
		//判断缓存中的登录状态码是否存在并且判断当前时间段与之前缓存的时间段是否小于
		if (login) {
			//当前时间段有效
			loginID = 1;
			uni.setStorageSync('LoginID', 1)
			if (lastFItemID != '') {
				if (lastFItemID != nowFItemID) {
					//先清空WeChatShop/SystemParam接口获取的数据
					uni.removeStorageSync('title');
					uni.removeStorageSync('imgBJ');
					resolve(loginID = 0);
				} else {
					onss().then(res => {
						//二次登录时，接口返回的数据处理
						if (res == 1) {
							//console.log('onLogin',res);
							resolve(loginID = res); //onLogin函数返回的状态码
						}
						//else{//console.log('onLogin',res)}
					}).catch(error => {
						//console.log('onss',error);
						// onLoginQuick(error).then(res => {
						// 	//console.log('onLoginQuick', res)
						// 	resolve(loginID = res); //onLoginQuick函数返回的状态码
						// }).catch(error => {
						// 	console.log('onLoginQuick', error)
						// });
					});
				}
			} else {
				onss().then(res => {
					//二次登录时，接口返回的数据处理
					if (res == 1) {
						//console.log('onLogin', res);
						resolve(loginID = res); //onLogin函数返回的状态码
					}
					//else {//console.log('onLogin',res)}
				}).catch(error => {
					//console.log('onss',error);
					onLoginQuick(error).then(res => {
						//console.log('onLoginQuick', res)
						resolve(loginID = res); //onLoginQuick函数返回的状态码
					}).catch(error => {
						//console.log('onLoginQuick', error)
					});
				});
			}
			//推荐人所推荐的公司id       
			uni.setStorage({
				key: 'FItemID',
				data: nowFItemID
			})
		} else {
			uni.setStorageSync('LoginID', 0)
			resolve(loginID = 0);
		}
	});
};
//登录前
function onss() {
	var head = null;
	var code = null;
	var twoLogin = 0;
	//登录事件前的判断
	var head = uni.getStorageSync('Token')
	if (head != undefined) {
		header = head;
	}
	uni.showLoading({
		title: '加载中',
	})
	let appid = uni.getStorageSync('appid'); //APPID 
	if (loginID != 0) {
		return new Promise((resolve, reject) => {
			let token = uni.getStorageSync('Token'),
				cookie = uni.getStorageSync('Cookies'),
				Url = uni.getStorageSync("URL") || Urls,
				url1;
			if (header != '') {
				twoLogin = 0;
				uni.setStorageSync('twoLogin', twoLogin);
				var hostid = uni.getStorageSync('lastHostid'); //服务器版本ID
				//console.log('hostid:' + hostid)
				uni.request({
					url: Url + 'WeChatShop/OnLoginQuick',
					// header: {
					// 	'auth': header,
					// 	'hostid': hostid,
					// 	'appid': appid,
					// },
					header: {
						'content-type': 'application/json', // 默认值
						'cookie': cookie,
						'token': token,
						'auth': token,
						'hostid': hostid,
						'appid': appid,
					},
					method: 'get',
					success: res => {
						reject(res)
					},
					fail: error => {
						reject(error)
					}
				})
			} else {
				twoLogin = 1;
				uni.setStorageSync('twoLogin', twoLogin);
				uni.login({ //登录
					success: res => {
						code = res.code;
						login(code).then(res => {
							//console.log('onLogin', res);
							resolve(loginID = res);
						}).catch(error => {
							//console.log('onLogin',error);
						});
					},
					fail: error => {
						//console.log('onLogin',error);
						// uni.showModal({
						// 	title: '友情提示',
						// 	content: '网络不稳定哦！！',
						// 	success: (res) => {
						// 		// wx.clearStorage();
						// 	}
						// })
						uni.hideLoading();
					}
				})
			}
		});
	} else {
		uni.hideLoading();
	}
};
//二次登录时，接口返回的数据处理
function onLoginQuick(res) {
	return new Promise((resolve, reject) => {
		if (res.data.status == 0) { //未登录
			uni.login({ //登录
				success: res => {
					let code = res.code;
					login2(code).then(res => {
						//console.log('onLogin', res);
						resolve(loginID = res);
					}).catch(error => {
						//console.log('onLogin',error);
					});
				}
			})
			// resolve(loginID = 0);
		} else if (res.data.status == 1) { //登录成功         
			if (res.data.data[0].FPhone != null) {
				FPhone = 1;
				uni.setStorage({
					key: 'Phone',
					data: res.data.data[0].FPhone
				})
			} else {
				FPhone = 0;
			}
			uni.setStorageSync('FPhone', FPhone) //是否有手机号
			getsetting().then(res => {
				resolve(loginID = res);
			}).catch(error => console.log(error));
		} else if (res.data.status == 2) { //登录后，信息不全(需补全信息)
			if (res.data.data[0].FPhone == null) {}
			var Mobile = '';
			res.data.data[0].FPhone == null ? Mobile = 0 : Mobile = 1;
			uni.setStorageSync('Mobile', Mobile);
			userinfo().then(res => {
				//console.log('userInfo',res);
				resolve(loginID = res);
			}) //.catch(error=>//console.log('userInfo',error));      
		}
		//else {//console.log('报错', res)}
	});
};

//getSetting 判断是否已授权
function getsetting() {
	let loginID = '';
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: res => {
				if (res.authSetting['scope.userInfo']) {
					// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
					uni.getUserInfo({
						withCredentials: true,
						lang: "zh_CN",
						success: res2 => {
							// app.globalData.userInfo = res2.userInfo;
							uni.setStorageSync('MuserInfo', res2.userInfo);
							uni.setStorageSync('isBeGranted', 1)
							phone();
						}
					})
					loginID = 1
				} else {
					uni.setStorageSync('isBeGranted', 0)
					uni.hideLoading();
					loginID = 0;
				}
				resolve(loginID)
			}
		});
	});
};

//补充信息
function userinfo() {
	let loginID = '';
	let appid = uni.getStorageSync('appid'); //APPID 
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: res => {
				if (res.authSetting['scope.userInfo']) {
					// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
					uni.getUserInfo({
						withCredentials: true,
						lang: "zh_CN",
						success: userRes => {      
							let FItemID = uni.getStorageSync('FItemID');
							//推荐人
							let parentID = uni.getStorageSync('parentID');
							if (parentID != '') {
								parentid = parentID
							} else {
								parentid = 0;
							}
							util('WeChatShop/GetUserInfo', {
								encryptedData: userRes.encryptedData,
								iv: userRes.iv,
								rawData: userRes.rawData,
								signature: userRes.signature,
								stockid: FItemID,
								appid: appid,
								parentID: parentid,
							}, 'POST').then(res => {
								// app.globalData.userInfo = userRes.userInfo;
								uni.setStorageSync('MuserInfo', userRes
									.userInfo)
								uni.setStorageSync('isBeGranted', 1);
								uni.setStorageSync('Phone', res.data[0].FPhone);
								//会员卡资料
								uni.setStorageSync('stockdata', res.stockdata[
									0])
									
								if (res.memberdata.length != 0) {
									uni.setStorageSync('memberdataID', 1)
									uni.setStorageSync('memberdata', res
										.memberdata);
								} else {
									uni.setStorageSync('memberdataID', 0)
									uni.removeStorageSync('memberdata');
								}
								phone();
								loginID = 1;
								resolve(loginID);
							}).catch(error => {
								uni.showModal({
									title: '提示',
									content: error.data.msg,
									success: res => {
										uni.removeStorageSync(
											'Token')
										uni.showModal({
											title: '提示',
											content: '登录出错，需要重新扫码进入',
										})
									}
								})
								uni.hideLoading();
								loginID = 0;
								resolve(loginID);
							})
						},
						//fail(error){//console.log(error)}
					})
				} else {
					isBeGranted = 0,
						uni.setStorageSync('isBeGranted', 0)
					uni.hideLoading();
					resolve(loginID = 0);
				}
			}
		})
	})
};

//登录，获取用户信息
function getUserInfo() {
	return new Promise((resolve, reject) => {
		uni.login({
			success: res => {
				// 发送 res.code 到后台换取 openId, sessionKey, unionId
				uni.getUserInfo({
					withCredentials: true,
					lang: "zh_CN",
					success: resUser => {
						//console.log(resUser);
						// app.globalData.userInfo = resUser.userInfo;
						resolve(1)
					},
					fail: error => {
						//console.log(error);
						resolve(0)
					}
				})
			}
		})
	})

};


//子拼团的跳转
function Childs(Newchildid) {
	let shareID = '';
	var self = this;
	return new Promise(function(resolve, reject) {
		//朋友帮忙砍价
		util('Sale/CutPriceJoin', {
			acid: acid,
			childid: Newchildid,
		}, 'POST').then(res => {
			//console.log(res);
			uni.showModal({
				title: '提示',
				content: '已为该活动砍价成功',
			})
			if (share == 1) {
				// callback(acid);
				shareID = 1;
			} else {
				onUserData();
				shareID = 1;
			}
			resolve(shareID)
		}).catch(error => {
			//console.log(error)
			uni.showToast({
				title: error.data.data,
				icon: 'none',
				duration: 2000,
			})
		})
	})
};

//分享
function onShare() {
	let FItemID = uni.getStorageSync('stockId'); //门店id
	var lastHostid = uni.getStorageSync('lastHostid'); //旧的
	let Uid = uni.getStorageSync('Uid');
	let chilData = {};
	// return new Promise((resolve, reject)=>{
	if (GroupData != '') {
		share = GroupData.share;
	}
	//console.log(Uid, share)
	// let share = '';
	if (Uid != '') {
		if (share == 0) {
			Uid = uid
		}

		// chilData = function chil(childSet){
		// let data = {};
		for (var i in childSet) {
			if (Uid == childSet[i].Uid) {
				chilData.childId = childSet[i].Childid;
				chilData.share = 0;
			}
		}
		//   return data;
		// }
		// chilData = chil(Uid,childSet);
		//console.log(chilData);
	} else {
		childId = '';
		Uid = '';
		share = 1;
	}
	if (id == 1) {
		Uid = '';
		share = 1;
	}
	//console.log(share)
	if (share) {
		share = 1;
	}
	let Sharedata = {
		id: id, //活动类型
		groupId: acid, //活动id
		childId: chilData.childId, //子活动id
		uid: Uid, //分享人id
		fItemID: FItemID, //门店id
		hostid: lastHostid, //服务器id
		share: share || chilData.share, //
	}
	return Sharedata;
	// })
};


function getTitle() {
	util('WeChatShop/MiniProgramName', {
		stockId: uni.getStorageSync('stockId')
	}, 'POST').then(res => {

	})
};

/**
 * 上拉刷新
 * pageNumber=>总数(该接口中有多少条数据)//所有内容的长度
 * pageIndex=>页码
 * pageSize=>每页的条数
 * 'Member/GetMemberDeposit'=>地址
 * callback=>回调函数
 */
const refresh = function(pageNumber, pageIndex, pageSize, url, callback) {
	let number = 0;
	/**
	 * 判断内容的长度是否能被10整除，值用来指向接口内容有几个页码。
	 *  能，值(number)则为商，不能，值(number)则为商+1
	 */
	if (pageNumber % pageSize === 0) {
		//求商
		number = pageNumber / pageSize;
	} else {
		//b=>求余
		var b = pageNumber / pageSize;
		//先转化为字符串，再分割
		var s = (b.toString()).split('.');
		number = parseInt(s[0]) + 1;
	}
	pageIndex += 1; //当前页码++
	//判断当前页码是否<= 总的页码
	if (pageIndex <= number) {
		util(url, {
			PageIndex: pageIndex,
			PageSize: pageSize
		}, 'GET').then(res => {
			return callback(res);
		}).catch(error => {
			return callback(error)
		});
	} else {
		uni.showToast({
			title: '已到底部了',
			icon: 'none',
			duration: 2000
		})
	}
};
/**
 * 
 * 动态高度
 * box=>节点名称，class=》.xxx  id=》 #xxx
 * list=>计算高度的列表，用来记录需要的高度个数
 * 动态高度 = 节点的高度 x 高度个数 + 上下间隔的距离
 * 
 *使用 wx.createSelectorQuery 的注意事项
 * 1、使用前一定要确认需要获取节点的元素已生成或加载完成，否则得到的null
 * 2、获取节点信息有两种方法
 *    1.query.exec(res=>{});
 *    2.query.select(节点名称).boundingClientRect(res=>{}).exec();
 */
function swiperHenght(box, list) {
	let number = list.length == 0 ? '1' : list.length;
	return new Promise((resolve, reject) => {
		const query = uni.createSelectorQuery()
		query.select(box).boundingClientRect(res => {
			let height;
			if (res == null) {
				height = 257; //这个是根据需求不同，而改变
			} else {
				height = res.height;
			}
			let sumHeigth = (height + 15) * number;
			resolve(sumHeigth)
		}).exec();
	});
}

export default {
	util: util,
	utils: utils,
	Login: Login,
	Login2: login2,
	login3:login3,
	onCountdown: onCountdown,
	miniProgram: miniProgram,
	swiperHenght: swiperHenght,
	refresh: refresh,
	getUrls: getUrls,
	post: post,
	get: get,
	SaleLogin: SaleLogin,
	getAuth: getAuth,
	aprom: aprom,
	add: add,
	childUser: childUser,
	getUserInfo: getUserInfo,
	Childs: Childs,
	onShare: onShare,
	GetTitle: getTitle,
	onjudge: onjudge
};
